<!DOCTYPE html>
<html lang="en">
  <head>
    <title>SwiftCoroutine  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>
    <script src="js/jquery.min.js" defer></script>
    <script src="js/jazzy.js" defer></script>
    
    <script src="js/lunr.min.js" defer></script>
    <script src="js/typeahead.jquery.js" defer></script>
    <script src="js/jazzy.search.js" defer></script>
  </head>
  <body>
    <a title="SwiftCoroutine  Reference"></a>
    <header>
      <div class="content-wrapper">
        <p><a href="index.html">SwiftCoroutine 2.1.9 Docs</a> (88% documented)</p>
        <p class="header-right">
          <form role="search" action="search.json">
            <input type="text" placeholder="Search documentation" data-typeahead>
          </form>
        </p>
      </div>
    </header>
    <div class="content-wrapper">
      <p id="breadcrumbs">
        <a href="index.html">SwiftCoroutine Reference</a>
        <img id="carat" src="img/carat.png" />
        SwiftCoroutine  Reference
      </p>
    </div>
    <div class="content-wrapper">
      <nav class="sidebar">
        <ul class="nav-groups">
          <li class="nav-group-name">
            <a href="Classes.html">Classes</a>
            <ul class="nav-group-tasks">
              <li class="nav-group-task">
                <a href="Classes/CoChannel.html">CoChannel</a>
              </li>
              <li class="nav-group-task">
                <a href="Classes/CoChannel/BufferType.html">– BufferType</a>
              </li>
              <li class="nav-group-task">
                <a href="Classes/CoChannel/Receiver.html">– Receiver</a>
              </li>
              <li class="nav-group-task">
                <a href="Classes/CoChannel/Sender.html">– Sender</a>
              </li>
              <li class="nav-group-task">
                <a href="Classes/CoFuture.html">CoFuture</a>
              </li>
              <li class="nav-group-task">
                <a href="Classes/CoPromise.html">CoPromise</a>
              </li>
              <li class="nav-group-task">
                <a href="Classes/CoScope.html">CoScope</a>
              </li>
            </ul>
          </li>
          <li class="nav-group-name">
            <a href="Enums.html">Enumerations</a>
            <ul class="nav-group-tasks">
              <li class="nav-group-task">
                <a href="Enums/CoChannelError.html">CoChannelError</a>
              </li>
              <li class="nav-group-task">
                <a href="Enums/CoFutureError.html">CoFutureError</a>
              </li>
              <li class="nav-group-task">
                <a href="Enums/CoroutineError.html">CoroutineError</a>
              </li>
            </ul>
          </li>
          <li class="nav-group-name">
            <a href="Extensions.html">Extensions</a>
            <ul class="nav-group-tasks">
              <li class="nav-group-task">
                <a href="Extensions/DispatchQueue.html">DispatchQueue</a>
              </li>
              <li class="nav-group-task">
                <a href="Extensions/Publisher.html">Publisher</a>
              </li>
              <li class="nav-group-task">
                <a href="Extensions/URLSession.html">URLSession</a>
              </li>
            </ul>
          </li>
          <li class="nav-group-name">
            <a href="Protocols.html">Protocols</a>
            <ul class="nav-group-tasks">
              <li class="nav-group-task">
                <a href="Protocols/CoCancellable.html">CoCancellable</a>
              </li>
              <li class="nav-group-task">
                <a href="Protocols/CoroutineScheduler.html">CoroutineScheduler</a>
              </li>
            </ul>
          </li>
          <li class="nav-group-name">
            <a href="Structs.html">Structures</a>
            <ul class="nav-group-tasks">
              <li class="nav-group-task">
                <a href="Structs/Coroutine.html">Coroutine</a>
              </li>
            </ul>
          </li>
        </ul>
      </nav>
      <article class="main-content">
        <section>
          <section class="section">
            
            <!--
  Title: SwiftCoroutine
  Description: Swift coroutines for iOS and macOS.
  Author: belozierov
  Keywords: swift, coroutines, coroutine, async/await
  -->

<p><img src="../master/Sources/logo.png" alt="Swift Coroutine"></p>

<p><img src="https://github.com/belozierov/SwiftCoroutine/workflows/macOS/badge.svg?branch=master" alt="macOS">
<img src="https://github.com/belozierov/SwiftCoroutine/workflows/Ubuntu/badge.svg?branch=master" alt="Ubuntu">
<a href="https://codecov.io/gh/belozierov/SwiftCoroutine"><img src="https://codecov.io/gh/belozierov/SwiftCoroutine/branch/master/graph/badge.svg" alt="codecov"></a>
<a href="https://codebeat.co/projects/github-com-belozierov-swiftcoroutine-master"><img src="https://codebeat.co/badges/748d64a5-efbc-436f-9aa6-2a8433de18aa" alt="codebeat badge"></a></p>

<p>Many languages, such as Kotlin, Go, JavaScript, Python, Rust, C#, C++ and others, already have <a href="https://en.wikipedia.org/wiki/Coroutine">coroutines</a> support that makes the <a href="https://en.wikipedia.org/wiki/Async/await">async/await</a> pattern implementation possible. This feature is not yet supported in Swift, but this can be improved by a framework without the need to change the language.</p>
<h4 id='main-features' class='heading'>Main features</h4>

<ul>
<li>It is the first implementation of <a href="https://en.wikipedia.org/wiki/Coroutine">coroutines</a> for Swift with iOS, macOS and Linux support.</li>
<li>It includes <a href="https://en.wikipedia.org/wiki/Futures_and_promises">futures</a> and <a href="https://en.wikipedia.org/wiki/Channel_(programming)">channels</a> that supplement coroutines for more flexibility.</li>
<li>It is completely <a href="https://en.wikipedia.org/wiki/Non-blocking_algorithm">lock-free</a> and uses only <a href="https://en.wikipedia.org/wiki/Compare-and-swap">atomic</a> primitives for synchronizations.</li>
</ul>
<h3 id='motivation' class='heading'>Motivation</h3>

<p>Asynchronous programming is usually associated with callbacks. It is quite convenient until there are too many of them and they start nesting. Then it&rsquo;s called a <strong>pyramid of doom</strong> or even <strong>callback hell</strong>.</p>

<p>Another problem of asynchronous programming is <strong>error handling</strong>, because Swift&rsquo;s natural error handling mechanism cannot be used.</p>
<h4 id='what-about-rx-and-other-such-frameworks' class='heading'>What about Rx and other such frameworks?</h4>

<p>There are many other frameworks that make it easy to use asynchronous code, such as Combine, RxSwift, PromiseKit and so on. They use other approaches that have some drawbacks:</p>

<ul>
<li>Similar to callbacks, you also need to create chained calls, that’s why you can’t normally use loops, exception handling, etc.</li>
<li>Usually you need to learn a complex new API with hundreds of methods.</li>
<li>Instead of working with the actual data, you need to operate with some wrappers all the time.</li>
<li>Chaining of errors can be really complicated to handle.</li>
</ul>
<h3 id='async-await' class='heading'>Async/await</h3>

<p>The <a href="https://en.wikipedia.org/wiki/Async/await">async/await</a> pattern is an alternative that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. </p>

<p>It is already well-established in other programming languages and is an evolution in asynchronous programming. The implementation of this pattern is possible thanks to coroutines.</p>

<p>Let’s have a look at the example with coroutine inside of which <code>await()</code> suspends it and resumes when the result is available without blocking the thread.</p>
<pre class="highlight swift"><code><span class="c1">//executes coroutine on the main thread</span>
<span class="kt">DispatchQueue</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="n">startCoroutine</span> <span class="p">{</span>

    <span class="c1">//extension that returns CoFuture&lt;(data: Data, response: URLResponse)&gt;</span>
    <span class="k">let</span> <span class="nv">dataFuture</span> <span class="o">=</span> <span class="kt">URLSession</span><span class="o">.</span><span class="n">shared</span><span class="o">.</span><span class="nf">dataTaskFuture</span><span class="p">(</span><span class="nv">for</span><span class="p">:</span> <span class="n">imageURL</span><span class="p">)</span>

    <span class="c1">//await CoFuture result that suspends coroutine and doesn't block the thread</span>
    <span class="k">let</span> <span class="nv">data</span><span class="p">:</span> <span class="kt">Data</span> <span class="o">=</span> <span class="k">try</span> <span class="n">dataFuture</span><span class="o">.</span><span class="nf">await</span><span class="p">()</span><span class="o">.</span><span class="n">data</span>

    <span class="c1">//create UIImage from the data</span>
    <span class="k">guard</span> <span class="k">let</span> <span class="nv">image</span> <span class="o">=</span> <span class="kt">UIImage</span><span class="p">(</span><span class="nv">data</span><span class="p">:</span> <span class="n">data</span><span class="p">)</span> <span class="k">else</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>

    <span class="c1">//execute heavy task on global queue and await the result without blocking the thread</span>
    <span class="k">let</span> <span class="nv">thumbnail</span><span class="p">:</span> <span class="kt">UIImage</span> <span class="o">=</span> <span class="k">try</span> <span class="kt">DispatchQueue</span><span class="o">.</span><span class="nf">global</span><span class="p">()</span><span class="o">.</span><span class="n">await</span> <span class="p">{</span> <span class="n">image</span><span class="o">.</span><span class="nf">makeThumbnail</span><span class="p">()</span> <span class="p">}</span>

    <span class="c1">//set image in UIImageView on the main thread</span>
    <span class="k">self</span><span class="o">.</span><span class="n">imageView</span><span class="o">.</span><span class="n">image</span> <span class="o">=</span> <span class="n">thumbnail</span>

<span class="p">}</span>
</code></pre>
<h3 id='documentation' class='heading'>Documentation</h3>

<p><a href="https://belozierov.github.io/SwiftCoroutine">API documentation</a></p>
<h3 id='requirements' class='heading'>Requirements</h3>

<ul>
<li>Support only 64-bit architectures</li>
<li>iOS 10+ / macOS 10.12+ / Ubuntu</li>
<li>Xcode 10.4+</li>
<li>Swift 5.2+</li>
</ul>
<h3 id='installation' class='heading'>Installation</h3>

<ul>
<li>It&rsquo;s available through the <a href="https://swift.org/package-manager">Swift Package Manager</a> for iOS, macOS and Linux.</li>
<li>It&rsquo;s available through <a href="https://cocoapods.org/pods/swiftcoroutine">CocoaPods</a> for iOS and macOS.</li>
</ul>
<h2 id='working-with-swiftcoroutine' class='heading'>Working with SwiftCoroutine</h2>
<h3 id='coroutines' class='heading'>Coroutines</h3>

<p>A <a href="https://en.wikipedia.org/wiki/Coroutine">coroutine</a> is a computation that can be suspended and resumed at a later time without blocking a thread. Coroutines build upon regular functions and can be executed on any scheduler with a possibility to switch among them during execution.</p>
<h4 id='key-benefits' class='heading'>Key benefits</h4>

<ul>
<li><strong>Suspend instead of block</strong>. The main advantage of coroutines is the ability to suspend their execution at some point without blocking a thread and resuming later on.</li>
<li><strong>Fast context switching</strong>. Switching between coroutines is much faster than switching between threads as it does not require the involvement of operating system.</li>
<li><strong>Asynchronous code in synchronous manner</strong>. The use of coroutines allows an asynchronous, non-blocking function to be structured in a manner similar to an ordinary synchronous function. And even though coroutines can run in multiple threads, your code will still look consistent and therefore easy to understand.</li>
</ul>
<h4 id='usage' class='heading'>Usage</h4>

<p>The coroutines API design is as minimalistic as possible. It consists of the <code><a href="Protocols/CoroutineScheduler.html">CoroutineScheduler</a></code> protocol that describes how to schedule coroutines (<code>DispatchQueue</code> already conforms it), and the <code><a href="Structs/Coroutine.html">Coroutine</a></code> structure with utility methods. This API is enough to do amazing things.</p>

<p>The following example shows the usage of  <code>await()</code> inside a coroutine to wrap asynchronous calls.</p>
<pre class="highlight swift"><code><span class="c1">//execute coroutine on the main thread</span>
<span class="kt">DispatchQueue</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="n">startCoroutine</span> <span class="p">{</span>

    <span class="c1">//await URLSessionDataTask response without blocking the thread</span>
    <span class="k">let</span> <span class="p">(</span><span class="nv">data</span><span class="p">,</span> <span class="nv">response</span><span class="p">,</span> <span class="nv">error</span><span class="p">)</span> <span class="o">=</span> <span class="k">try</span> <span class="kt">Coroutine</span><span class="o">.</span><span class="n">await</span> <span class="p">{</span> <span class="n">callback</span> <span class="k">in</span>
        <span class="kt">URLSession</span><span class="o">.</span><span class="n">shared</span><span class="o">.</span><span class="nf">dataTask</span><span class="p">(</span><span class="nv">with</span><span class="p">:</span> <span class="n">url</span><span class="p">,</span> <span class="nv">completionHandler</span><span class="p">:</span> <span class="n">callback</span><span class="p">)</span><span class="o">.</span><span class="nf">resume</span><span class="p">()</span>
    <span class="p">}</span>

    <span class="o">.</span> <span class="o">.</span> <span class="o">.</span> <span class="n">use</span> <span class="n">response</span> <span class="n">on</span> <span class="n">the</span> <span class="n">main</span> <span class="n">thread</span> <span class="o">.</span> <span class="o">.</span> <span class="o">.</span> 
<span class="p">}</span>
</code></pre>

<p>Here&rsquo;s how we can conform <code>NSManagedObjectContext</code> to <code><a href="Protocols/CoroutineScheduler.html">CoroutineScheduler</a></code> for launching coroutines on it.</p>
<pre class="highlight swift"><code><span class="kd">extension</span> <span class="kt">NSManagedObjectContext</span><span class="p">:</span> <span class="kt">CoroutineScheduler</span> <span class="p">{</span>

    <span class="kd">func</span> <span class="nf">scheduleTask</span><span class="p">(</span><span class="n">_</span> <span class="nv">task</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span> <span class="p">{</span>
        <span class="nf">perform</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
    <span class="p">}</span>

<span class="p">}</span>

<span class="c1">//execute coroutine on the main thread</span>
<span class="kt">DispatchQueue</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="n">startCoroutine</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">context</span><span class="p">:</span> <span class="kt">NSManagedObjectContext</span> <span class="c1">//context with privateQueueConcurrencyType</span>
    <span class="k">let</span> <span class="nv">request</span><span class="p">:</span> <span class="kt">NSFetchRequest</span><span class="o">&lt;</span><span class="kt">NSDictionary</span><span class="o">&gt;</span> <span class="c1">//some complex request</span>

    <span class="c1">//execute request on the context without blocking the main thread</span>
    <span class="k">let</span> <span class="nv">result</span><span class="p">:</span> <span class="p">[</span><span class="kt">NSDictionary</span><span class="p">]</span> <span class="o">=</span> <span class="k">try</span> <span class="n">context</span><span class="o">.</span><span class="n">await</span> <span class="p">{</span> <span class="k">try</span> <span class="n">context</span><span class="o">.</span><span class="nf">fetch</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre>
<h3 id='futures-and-promises' class='heading'>Futures and Promises</h3>

<p>A future is a read-only holder for a result that will be provided later and the promise is the provider of this result. They represent the eventual completion or failure of an asynchronous operation.</p>

<p>The <a href="https://en.wikipedia.org/wiki/Futures_and_promises">futures and promises</a> approach itself has become an industry standart. It is a convenient mechanism to synchronize asynchronous code. But together with coroutines, it takes the usage of asynchronous code to the next level and has become a part of the async/await pattern. If coroutines are a skeleton, then futures and promises are its muscles.</p>
<h4 id='main-features' class='heading'>Main features</h4>

<ul>
<li><strong>Performance</strong>. It is much faster than most of other futures and promises implementations.</li>
<li><strong>Awaitable</strong>. You can await the result inside the coroutine.</li>
<li><strong>Cancellable</strong>. You can cancel the whole chain as well as handle it and complete the related actions.</li>
</ul>
<h4 id='usage' class='heading'>Usage</h4>

<p>Futures and promises are represented by the corresponding <code><a href="Classes/CoFuture.html">CoFuture</a></code> class and its <code><a href="Classes/CoPromise.html">CoPromise</a></code> subclass. </p>
<pre class="highlight swift"><code><span class="c1">//wraps some async func with CoFuture</span>
<span class="kd">func</span> <span class="nf">makeIntFuture</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">CoFuture</span><span class="o">&lt;</span><span class="kt">Int</span><span class="o">&gt;</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">promise</span> <span class="o">=</span> <span class="kt">CoPromise</span><span class="o">&lt;</span><span class="kt">Int</span><span class="o">&gt;</span><span class="p">()</span>
    <span class="n">someAsyncFunc</span> <span class="p">{</span> <span class="n">int</span> <span class="k">in</span>
        <span class="n">promise</span><span class="o">.</span><span class="nf">success</span><span class="p">(</span><span class="n">int</span><span class="p">)</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">promise</span>
<span class="p">}</span>
</code></pre>

<p>It allows to start multiple tasks in parallel and synchronize them later with <code>await()</code>.</p>
<pre class="highlight swift"><code><span class="c1">//create CoFuture&lt;Int&gt; that takes 2 sec. from the example above </span>
<span class="k">let</span> <span class="nv">future1</span><span class="p">:</span> <span class="kt">CoFuture</span><span class="o">&lt;</span><span class="kt">Int</span><span class="o">&gt;</span> <span class="o">=</span> <span class="nf">makeIntFuture</span><span class="p">()</span>

<span class="c1">//execute coroutine on the global queue and returns CoFuture&lt;Int&gt; with future result</span>
<span class="k">let</span> <span class="nv">future2</span><span class="p">:</span> <span class="kt">CoFuture</span><span class="o">&lt;</span><span class="kt">Int</span><span class="o">&gt;</span> <span class="o">=</span> <span class="kt">DispatchQueue</span><span class="o">.</span><span class="nf">global</span><span class="p">()</span><span class="o">.</span><span class="n">coroutineFuture</span> <span class="p">{</span>
    <span class="k">try</span> <span class="kt">Coroutine</span><span class="o">.</span><span class="nf">delay</span><span class="p">(</span><span class="o">.</span><span class="nf">seconds</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span> <span class="c1">//some work that takes 3 sec.</span>
    <span class="k">return</span> <span class="mi">6</span>
<span class="p">}</span>

<span class="c1">//execute coroutine on the main thread</span>
<span class="kt">DispatchQueue</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="n">startCoroutine</span> <span class="p">{</span>
    <span class="k">let</span> <span class="nv">sum</span><span class="p">:</span> <span class="kt">Int</span> <span class="o">=</span> <span class="k">try</span> <span class="n">future1</span><span class="o">.</span><span class="nf">await</span><span class="p">()</span> <span class="o">+</span> <span class="n">future2</span><span class="o">.</span><span class="nf">await</span><span class="p">()</span> <span class="c1">//will await for 3 sec.</span>
    <span class="k">self</span><span class="o">.</span><span class="n">label</span><span class="o">.</span><span class="n">text</span> <span class="o">=</span> <span class="s">"Sum is </span><span class="se">\(</span><span class="n">sum</span><span class="se">)</span><span class="s">"</span>
<span class="p">}</span>
</code></pre>

<p>It&rsquo;s very easy to transform or compose <code><a href="Classes/CoFuture.html">CoFuture</a></code>s into a new one.</p>
<pre class="highlight swift"><code><span class="k">let</span> <span class="nv">array</span><span class="p">:</span> <span class="p">[</span><span class="kt">CoFuture</span><span class="o">&lt;</span><span class="kt">Int</span><span class="o">&gt;</span><span class="p">]</span>

<span class="c1">//create new CoFuture&lt;Int&gt; with sum of future results</span>
<span class="k">let</span> <span class="nv">sum</span> <span class="o">=</span> <span class="kt">CoFuture</span> <span class="p">{</span> <span class="k">try</span> <span class="n">array</span><span class="o">.</span><span class="nf">reduce</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="p">{</span> <span class="k">try</span> <span class="nv">$0</span> <span class="o">+</span> <span class="nv">$1</span><span class="o">.</span><span class="nf">await</span><span class="p">()</span> <span class="p">}</span> <span class="p">}</span>
</code></pre>
<h3 id='channels' class='heading'>Channels</h3>

<p>Futures and promises provide a convenient way to transfer a single value between coroutines. <a href="https://en.wikipedia.org/wiki/Channel_(programming)">Channels</a> provide a way to transfer a stream of values. Conceptually, a channel is similar to a queue that allows to suspend a coroutine on receive if it is empty, or on send if it is full.</p>

<p>This non-blocking primitive is widely used in such languages as Go and Kotlin, and it is another instrument that improves working with coroutines.</p>
<h4 id='usage' class='heading'>Usage</h4>

<p>To create channels, use the <code><a href="Classes/CoChannel.html">CoChannel</a></code> class.</p>
<pre class="highlight swift"><code><span class="c1">//create a channel with a buffer which can store only one element</span>
<span class="k">let</span> <span class="nv">channel</span> <span class="o">=</span> <span class="kt">CoChannel</span><span class="o">&lt;</span><span class="kt">Int</span><span class="o">&gt;</span><span class="p">(</span><span class="nv">capacity</span><span class="p">:</span> <span class="mi">1</span><span class="p">)</span>

<span class="kt">DispatchQueue</span><span class="o">.</span><span class="nf">global</span><span class="p">()</span><span class="o">.</span><span class="n">startCoroutine</span> <span class="p">{</span>
    <span class="k">for</span> <span class="n">i</span> <span class="k">in</span> <span class="mi">0</span><span class="o">..&lt;</span><span class="mi">100</span> <span class="p">{</span>
        <span class="c1">//imitate some work</span>
        <span class="k">try</span> <span class="kt">Coroutine</span><span class="o">.</span><span class="nf">delay</span><span class="p">(</span><span class="o">.</span><span class="nf">seconds</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
        <span class="c1">//sends a value to the channel and suspends coroutine if its buffer is full</span>
        <span class="k">try</span> <span class="n">channel</span><span class="o">.</span><span class="nf">awaitSend</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
    <span class="p">}</span>

    <span class="c1">//close channel when all values are sent</span>
    <span class="n">channel</span><span class="o">.</span><span class="nf">close</span><span class="p">()</span>
<span class="p">}</span>

<span class="kt">DispatchQueue</span><span class="o">.</span><span class="nf">global</span><span class="p">()</span><span class="o">.</span><span class="n">startCoroutine</span> <span class="p">{</span>
    <span class="c1">//receives values until closed and suspends a coroutine if it's empty</span>
    <span class="k">for</span> <span class="n">i</span> <span class="k">in</span> <span class="n">channel</span><span class="o">.</span><span class="nf">makeIterator</span><span class="p">()</span> <span class="p">{</span>
        <span class="nf">print</span><span class="p">(</span><span class="s">"Receive"</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
    <span class="p">}</span>

    <span class="nf">print</span><span class="p">(</span><span class="s">"Done"</span><span class="p">)</span>
<span class="p">}</span>
</code></pre>
<h3 id='scope' class='heading'>Scope</h3>

<p>All launched coroutines, <code><a href="Classes/CoFuture.html">CoFuture</a></code>s and <code><a href="Classes/CoChannel.html">CoChannel</a></code>s, usually do not need to be referenced. They are deinited after their execution. But often there is a need to complete them earlier, when they are no longer needed. For this, <code><a href="Classes/CoFuture.html">CoFuture</a></code> and <code><a href="Classes/CoChannel.html">CoChannel</a></code> have methods for canceling.</p>

<p><code><a href="Classes/CoScope.html">CoScope</a></code> makes it easier to manage the life cycle of these objects. It allows you to keep weak references to them and cancel if necessary or on deinit.</p>
<h4 id='usage' class='heading'>Usage</h4>

<p>You can add coroutines, <code><a href="Classes/CoFuture.html">CoFuture</a></code>s, <code><a href="Classes/CoChannel.html">CoChannel</a></code>s and other <code><a href="Protocols/CoCancellable.html">CoCancellable</a></code> to <code><a href="Classes/CoScope.html">CoScope</a></code> to cancel them when they are no longer needed or on deinit.</p>
<pre class="highlight swift"><code><span class="kd">class</span> <span class="kt">ViewController</span><span class="p">:</span> <span class="kt">UIViewController</span> <span class="p">{</span>

    <span class="k">let</span> <span class="nv">scope</span> <span class="o">=</span> <span class="kt">CoScope</span><span class="p">()</span> <span class="c1">//will cancel all objects on `cancel()` or deinit</span>

    <span class="kd">func</span> <span class="nf">performSomeWork</span><span class="p">()</span> <span class="p">{</span>
        <span class="c1">//create new `CoChannel` and add to `CoScope`</span>
        <span class="k">let</span> <span class="nv">channel</span> <span class="o">=</span> <span class="nf">makeSomeChannel</span><span class="p">()</span><span class="o">.</span><span class="nf">added</span><span class="p">(</span><span class="nv">to</span><span class="p">:</span> <span class="n">scope</span><span class="p">)</span>

        <span class="c1">//execute coroutine and add to `CoScope`</span>
        <span class="kt">DispatchQueue</span><span class="o">.</span><span class="n">main</span><span class="o">.</span><span class="nf">startCoroutine</span><span class="p">(</span><span class="nv">in</span><span class="p">:</span> <span class="n">scope</span><span class="p">)</span> <span class="p">{</span> <span class="p">[</span><span class="k">weak</span> <span class="k">self</span><span class="p">]</span> <span class="k">in</span>
            <span class="k">for</span> <span class="n">item</span> <span class="k">in</span> <span class="n">channel</span><span class="o">.</span><span class="nf">makeIterator</span><span class="p">()</span> <span class="p">{</span>
                <span class="k">try</span> <span class="k">self</span><span class="p">?</span><span class="o">.</span><span class="nf">performSomeWork</span><span class="p">(</span><span class="nv">with</span><span class="p">:</span> <span class="n">item</span><span class="p">)</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="kd">func</span> <span class="nf">performSomeWork</span><span class="p">(</span><span class="n">with</span> <span class="nv">item</span><span class="p">:</span> <span class="kt">Item</span><span class="p">)</span> <span class="k">throws</span> <span class="p">{</span>
        <span class="c1">//create new `CoFuture` and add to `CoScope`</span>
        <span class="k">let</span> <span class="nv">future</span> <span class="o">=</span> <span class="nf">makeSomeFuture</span><span class="p">(</span><span class="n">item</span><span class="p">)</span><span class="o">.</span><span class="nf">added</span><span class="p">(</span><span class="nv">to</span><span class="p">:</span> <span class="n">scope</span><span class="p">)</span>

        <span class="k">let</span> <span class="nv">result</span> <span class="o">=</span> <span class="k">try</span> <span class="n">future</span><span class="o">.</span><span class="nf">await</span><span class="p">()</span>
        <span class="o">.</span> <span class="o">.</span> <span class="o">.</span> <span class="k">do</span> <span class="kd">some</span> <span class="n">work</span> <span class="n">using</span> <span class="n">result</span> <span class="o">.</span> <span class="o">.</span> <span class="o">.</span>
    <span class="p">}</span>

<span class="p">}</span>
</code></pre>

          </section>
        </section>
        <section id="footer">
          <p>&copy; 2020 <a class="link" href="https://github.com/belozierov/SwiftCoroutine" target="_blank" rel="external">Alex Belozierov</a>. All rights reserved. (Last updated: 2020-07-11)</p>
          <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.13.5</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p>
        </section>
      </article>
    </div>
  </body>
</div>
</html>
